/**
 * 
 */
package pl.net.beercrm.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import pl.net.beercrm.dao.GenericDao;
import pl.net.beercrm.model.Analysis;

/**
 * @author Rafi
 * 
 */
@Service
@Transactional(propagation = Propagation.REQUIRES_NEW)
public class AnalysisService implements GenericService<Analysis, Long> {

	@Autowired
	private GenericDao<Analysis, Long> analysisDao;

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.net.beercrm.service.GenericService#upsert(java.lang.Object)
	 */
	@Override
	public void upsert(Analysis object) {
		List<Analysis> objectList = findByGuid(object.getCustomer());
		
		if(objectList.size() > 0) {
			Analysis persistedAnalysis = objectList.get(0);
			persistedAnalysis.setDate(object.getDate());
			persistedAnalysis.setDiscount(object.getDiscount());
			persistedAnalysis.setDiscountStart(object.getDiscountStart());
			persistedAnalysis.setDiscountExpiry(object.getDiscountExpiry());
			persistedAnalysis.setFavoriteBrand(object.getFavoriteBrand());
			persistedAnalysis.setIngredientMatch(object.getIngredientMatch());
			persistedAnalysis.setPriceMatch(object.getPriceMatch());
			persistedAnalysis.setRegionMatch(object.getRegionMatch());
			analysisDao.update(persistedAnalysis);
		} else {
			analysisDao.create(object);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.net.beercrm.service.GenericService#delete(java.lang.Object)
	 */
	@Override
	public void delete(Analysis object) {
		List<Analysis> persistedObjects = findByGuid(object.getCustomer());
		for (Analysis analysis : persistedObjects) {
			analysisDao.delete(analysis);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.net.beercrm.service.GenericService#find(java.io.Serializable)
	 */
	@Override
	public Analysis find(Long id) {
		return analysisDao.findById(id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.net.beercrm.service.GenericService#findByGuid(java.lang.String)
	 */
	@Override
	public List<Analysis> findByGuid(String guid) {
		return analysisDao.findAllByProperty("customer", guid);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.net.beercrm.service.GenericService#list()
	 */
	@Override
	public List<Analysis> list() {
		return analysisDao.findAll();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * pl.net.beercrm.service.GenericService#findByProperty(java.lang.String,
	 * java.lang.Object)
	 */
	@Override
	public List<Analysis> findByProperty(String property, Object value) {
		return analysisDao.findAllByProperty(property, value);
	}

}
